
function regJsonEditor(amisLib, React) {
    function JsonEditorComponent(props) {
        const [val, setVal] = React.useState(props.$schema.value);
          const [len, setLen] = React.useState(props.$schema.maxlen);
    

        function stripHtmlTags(html) {
            // 使用正则表达式匹配并移除所有HTML标签
            let result = html.replace(/<[^>]+>/g, '');
            return result;
        }
        
        function parseSpan(html){
            console.log('parseSpan1', html, typeof html);
            let arr = [];
            const matches = html.matchAll(/<span(.*?)>(.*?)<\/span>/g);//matchAll
            for (let match of matches) {
                console.log(match); // 输出每一对匹配的 "span"标签
                
                let str = html.substr(0,match.index);
                
                let offset = stripHtmlTags(str).length;
                
                let txtLen = match[2].length; //$(match[0]).text().length; 
                arr.push({
                    "type": 'STYLE_UNDERLINE',
                    "offset": offset,
                    "length": txtLen,
                    "depth": 0
                })
                
            }
            
            return arr;
        }
        
        function parseStrong(html){
            console.log('parseStrong', html);
            let arr = [];
            const matches = html.matchAll(/<strong(.*?)>(.*?)<\/strong>/g);//matchAll
            for (let match of matches) {
                console.log('parseStrong',match); // 输出每一对匹配的 "strong"标签
                
                let str = html.substr(0,match.index);
                
                let offset = stripHtmlTags(str).length;
                
                let txtLen = match[2].length; //$(match[0]).text().length; 
                arr.push({
                    "type": 'STYLE_BOLD',
                    "offset": offset,
                    "length": txtLen,
                    "depth": 0
                })
                
            }
            
            return arr;
        }
        
        function parseItalic(html){
            console.log('parseItalic', html);
            let arr = [];
            const matches = html.matchAll(/<em(.*?)>(.*?)<\/em>/g);//matchAll
            for (let match of matches) {
                console.log('parseItalic',match); // 输出每一对匹配的 "em"标签
                
                let str = html.substr(0,match.index);
                
                let offset = stripHtmlTags(str).length;
                
                let txtLen = match[2].length; //$(match[0]).text().length; 
                arr.push({
                    "type": 'STYLE_ITALIC',
                    "offset": offset,
                    "length": txtLen,
                    "depth": 0
                })
            }
            return arr;
        }
        
        
        //解析样式  斜体：<em>是是是</em>，粗体：<strong>喔喔</strong>
        const parsSty = (html) => {
            console.log('html111', html);
            // let parser = new DOMParser();
            // let doc = parser.parseFromString(html, "text/html");
            // console.log('doc111', doc);
            
            let spanarr = parseSpan(html);
            let strongarr = parseStrong(html);
            let iarr = parseItalic(html);
            
            return [...spanarr,...strongarr,...iarr];
        }
        //解析P标签
        const parsP = (html_) => {
          let html = `<p>${html_}</p>`;
          
            console.log('parsP', html);
            if(html === '&nbsp;'){
                return {
                    value: ' ',
                    decoratorSet: []
                }
            }
            let text = $(html).text().replace(/\\n/ig, '');
            if (text === '') {
                return {
                    value: '',
                    decoratorSet: []
                }
            } else {
                //找出加粗，下划线，和倾斜 span
                let arr = parsSty(html);
                return {
                    value: text,
                    decoratorSet: arr
                }
            }
        }
        //解析UL标签
        const parsUL = (html_) => {
            let html = '<ul>'+html_+'</ul>';
            console.log('parsUL', html);
            let text = $(html).text().replace(/\\n/ig, '');
            let arr = [];
    
            arr.push({
                "type": "LIST_UNORDERED",
                "offset": 0,
                "length": text.length,
                "depth": 0
            })
            let offset = 0;
            $(html).children().each(function(index, value) {
                let item = $(value);
                let itemTxt = item.text();
                console.log("parsUL->li->"+index,itemTxt)
                arr.push({
                    "type": "LIST_ITEM",
                    "offset": offset,
                    "length": itemTxt.length,
                    "depth": 0
                })
                offset += itemTxt.length;
            });
            
            //找出加粗，下划线，和倾斜 span
            let arr2 = parsSty(html);
            return {
                value: text,
                decoratorSet: [...arr, ...arr2]
            }
        }
        //解析OL标签
        const parsOL = (html_) => {
            let html = '<ol>'+html_+'</ol>';
            console.log('parsOL', html);
            let text = $(html).text().replace(/\\n/ig, '');
            let arr = [];
    
            arr.push({
                "type": "LIST_ORDERED",
                "offset": 0,
                "length": text.length,
                "depth": 0
            })
            let offset = 0;
            $(html).children().each(function(index, value) {
                let item = $(value);
                let itemTxt = item.text();
                arr.push({
                    "type": "LIST_ITEM",
                    "offset": offset,
                    "length": itemTxt.length,
                    "depth": 0
                })
                offset += itemTxt.length;
            });
            //找出加粗，下划线，和倾斜 span
            let arr2 = parsSty(html);
            return {
                value: text,
                decoratorSet: [...arr, ...arr2]
            }
        }
        const htmlToJson = (html) => {
        
            // console.log('html,',html)
            //使用jquery库解析
            let $ctx__ = $('<div>' + html + '</div>');
            let jsonVal_ = [];
            $ctx__.children().each(function(index, val) {
                // console.log("序列：" + index + ", 值：" + value);
                let tag = $(val)[0].tagName;
                let value = $(val).html();
                console.log("tag1：", tag);
                console.log("tag2：", value);
                if (tag === 'P') {
                    jsonVal_.push(parsP(value));
                } else if (tag === 'UL') {
                    jsonVal_.push(parsUL(value));
                } else if (tag === 'OL') {
                    jsonVal_.push(parsOL(value));
                }
            });
            console.log('jsonVal_', jsonVal_);
            return jsonVal_;
        }
        const jsonToHtml = (json) => {
            let jsonVal = [];
            let html = [];
            jsonVal = json;// findNode(json,false);
            console.log('jsonVal', jsonVal);
            if (jsonVal.length > 0) {
                for (let i = 0; i < jsonVal.length; i++) {
                    let el = jsonVal[i];
                    if (el.value.length === 0 && el.decoratorSet.length === 0) {
                        html.push('<p></p>');
                    } else if (el.value.length > 0 && el.decoratorSet.length === 0) {
                        
                        html.push('<p>' + el.value + '</p>');
                    } else if (el.value.length > 0 && el.decoratorSet.length > 0) {
                        //点：ul->li  数字：ol->li
                        let li_list = [];
                        let wraper = el.decoratorSet[0].type === 'LIST_UNORDERED' ? 'ul' : 'ol'; //ul or ol
                        let html__ = [];
                    
                        for (let k = 0; k < el.decoratorSet.length; k++) {
                            let ds = el.decoratorSet[k];
                            if (ds.type === 'LIST_ITEM') {
                                li_list.push(`<li>${el.value.substr(ds.offset,ds.length)}</li>`);
                            }
                        }
                        
                        //处理样式,先取出样式影响的字符串，然后在对应的位置插入带标签的字符串
                        let decoratorSets = el.decoratorSet.filter(p => p.type === 'STYLE_UNDERLINE' ||
                        p.type==='STYLE_BOLD' ||
                        p.type==='STYLE_ITALIC');
                        
                        decoratorSets.sort((a, b) => b.offset - a.offset);
                        for (let k = 0; k < decoratorSets.length; k++) {
                            let ds = decoratorSets[k];
                            ds.value = el.value.substr(ds.offset,ds.length);
                        }
                        for (let k = 0; k < decoratorSets.length; k++) {
                            let ds = decoratorSets[k];
                            let tpl = '';
                            if(ds.type === 'STYLE_UNDERLINE'){//处理下划线
                                tpl = `<span style="text-decoration: underline;">${ds.value}</span>`;
                            }else if(ds.type === 'STYLE_BOLD'){//处理加粗
                                tpl = `<strong>${ds.value}</strong>`
                            }else if(ds.type === 'STYLE_ITALIC'){//处理倾斜
                                tpl = `<em>${ds.value}</em>`
                            }
                            el.value = el.value.substring(0,ds.offset) + tpl + el.value.substring(ds.offset + ds.length,el.value.length);
                        }
                        html__ = `<${wraper}>${li_list.join('')}</${wraper}>`
                        html.push(html__)
                    }
                }
            }
            return html.join('');
        }
    
        console.log("props", props)
        let dir = props.formMode; //"horizontal"
        let value = props.$schema.value;
        let defaultHtml = '';
        if (value) {
            defaultHtml = jsonToHtml(value);
            // console.log('defaultHtml', defaultHtml);
        }
        let sc = {
            "type": "input-rich-text",
            "name": props.name + '_',
            "value": defaultHtml,
            "onEvent": {
                "change": {
                    "actions": [{
                        "actionType": "custom",
                        // "script": "this.htmlToJson(event.data);event.stopPropagation();"
                        "script": (context, doAction, event) => {
                            let json_ = htmlToJson(event.data[props.name + '_']);
                            // let jsonVal_ = findNode(val,json_);
                            // setVal(jsonVal_);
                            setVal(json_)
                            console.log('props.$schema.real',props.$schema.real);
                            // console.log('json_', json_);
                            // 第二个参数是要修改的表单项名称
                            // onChange('new name', 'username');
                            // context.props.onChange(event.data[props.name + '_'], props.name+'_');									// console.log('doAction',doAction);
                            // context.props.onChange('aaaaaaaaaaa', props.name);
                            // window.abc = context;
                            // window.abc2 = doAction;
                            // window.abc3 = event;
                    
                            event.context.scoped.parent.component.props.data[props.$schema.real] = json_;
                            event.context.scoped.parent.component.forceUpdate();

                            console.log('最新的值',event.data[props.name+'_']);
                        }
                    }]
                }
            }
            ,
            "options": {
                "menubar": false,
                  // "maxlength":len,
                "height": 200,
                "plugins": [
                    // "advlist",
                    // "autolink",
                    // "link",
                    // "image",
                    "lists",
                    // "charmap",
                    // "preview",
                    // "anchor",
                    // "pagebreak",
                    // "searchreplace",
                    // "wordcount",
                    // "visualblocks",
                    // "visualchars",
                    // "code",
                    // "fullscreen",
                    // "insertdatetime",
                    // "media",
                    // "nonbreaking",
                    // "table",
                    // "emoticons",
                    // "template",
                    "underline",
                    // "help"
                ],
                "toolbar": "bold italic underline | bullist numlist"
            }
        };

    
        const createEditor = () => {
            return amisLib.render(sc);
        }
        const createFormLabel = () => {
            return React.createElement('label', {
                    className: 'cxd-Form-label cxd-Form-itemColumn--normal'
                },
                null,
                React.createElement('span', {
                    className: 'cxd-TplField'
                }, props.label)
            )
        }
        const createFormValue = () => {
            return React.createElement('div', {
                    className: 'cxd-Form-value'
                },
                null,
                React.createElement('div', {
                    className: 'cxd-Form-control cxd-RichTextControl'
                }, null, createEditor())
            )
        }
        const createFormItem = () => {
            return React.createElement('div', {
                    className: 'cxd-Form-item cxd-Form-item--' + dir,
                    dataRole: 'form-item',
                    dataAmisName: props.name,
                },
                null,
                [createFormLabel(), createFormValue()]
            );
        }
    
        return createFormItem();
    }
    //注册自定义组件，请参考后续对工作原理的介绍
    amisLib.Renderer({
        test: /(^|\/)richjson/
    })(JsonEditorComponent);
}

(function() {
    let amisLib = amisRequire('amis');
    let React = amisRequire('react');

    //注册自定义组件
    regJsonEditor(amisLib, React);
})();